/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.GlobalVariable;
import org.gl.android.activity.ImageUploadActivity;
import org.gl.customview.PullToRefreshView;
import org.gl.customview.PullToRefreshView.OnFooterRefreshListener;
import org.gl.customview.PullToRefreshView.OnHeaderRefreshListener;
import org.gl.ui.manger.AjaxCallBackProxy;
import org.gl.utils.Tip;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.adapters.SimpleCustomAdapter;
import com.chanceit.ssss.common.IntentExtraDataKey;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * the all message list that has send
 * 
 * @author Administrator
 * 
 */
public class MessageCenterMessageListFragment extends BaseFragment implements
		OnItemClickListener, OnHeaderRefreshListener, OnFooterRefreshListener,
		View.OnClickListener {
	OnFragmentEvent mCallback;
	private String imageUrl;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
	// String[] keys = new String[] { "recipient", "messageContent",
	// "createTime",
	// "messageTitle", "creator", "messageId" };
	String[] keys = new String[] { "messageTitle", "", "createTime",
			"messageContent", "messageImage" };
	protected JSONArray userListJosnAry = new JSONArray();
	SimpleCustomAdapter adapter;
	int page = 1;
	EditText editText1;

	// The container Activity must implement this interface so the frag can
	// deliver messages
	public interface OnListFragmentSelectedListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onArticleSelected(int position);

		public void onFragmentClick(int id);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	ListView listView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.message_box_list, container, false);
		listView = (ListView) view.findViewById(R.id.order_carer_lv);
		listView.setOnItemClickListener(this);

		mPullToRefreshView = (PullToRefreshView) (view
				.findViewById(R.id.main_pull_refresh_view));
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		initData();
		// 判断是否显示消息发送按钮 FIXME 根据权限
//		if (GlobalVariable.role == ShopRole.ADMIN
//				|| GlobalVariable.role == ShopRole.SALEMANGER) {
			view.findViewById(R.id.ll_sendmessage).setVisibility(View.VISIBLE);
			view.findViewById(R.id.sendMessage).setOnClickListener(this);
			view.findViewById(R.id.pickImage).setOnClickListener(this);
//		}
		editText1 = (EditText) view.findViewById(R.id.editText1);
		return view;
	}

	PullToRefreshView mPullToRefreshView;

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {

				page++;
				getdata(page);
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page = 1;
				getdata(page);
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}

	private void initData() {
		if (adapter != null && userListJosnAry != null
				&& userListJosnAry.length() > 0) {
			setListAdapter(adapter);
			lg.i(TAG, "resotre the fragment");
			return;
		}
		getdata(null);

	}

	private void getdata(Integer _page) {// FIXME 只能通过设备识别码获取单发消息列表
		String identifier = IntentExtraDataKeyValue.getUserIdentifier();
		ds.getmessageList(_page, null, "0", null, GlobalVariable
				.getGlobalInstance().intent
				.getStringExtra(IntentExtraDataKey.COMPANYID), identifier,
				null, new AjaxCallBack<String>() {
					@Override
					public void onStart() {
						super.onStart();
						loading();
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						loadFailed(strMsg);
					}

					public void onSuccess(String t) {
						lg.i(TAG, t);
						int code = 0;
						String mesage = "";
						try {
							JSONObject result = new JSONObject(t);
							;
							code = result.optInt(webkey.code);
							mesage = result.optString(webkey.reason);

							JSONArray newJsonArray = result
									.optJSONArray(webkey.result);
							contents.removeAll(contents);
							if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
								userListJosnAry = null;
								userListJosnAry = newJsonArray;
							} else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
								for (int i = 0; i < newJsonArray.length(); i++) {
									userListJosnAry.put(newJsonArray.opt(i));
								}
							}
							if (userListJosnAry == null) {
								userListJosnAry = new JSONArray();
							}
							int count = userListJosnAry.length();
							for (int i = 0; i < count; i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								JSONObject temp = userListJosnAry
										.getJSONObject(i);
								for (String key : keys) {
									Object o = temp.opt(key);
									if (o == null) {
										o = "";
									}
									if (key.equals("messageTitle")) {
										if (o.toString().length() > 4) {
											o = o.toString().substring(0, 4);
										}
										o = "【" + o.toString() + "】";
									}
									map.put(key, o.toString());
								}
								contents.add(map);
							}
							if (adapter == null) {
								if (contents.size() > 0) {
									adapter = new SimpleCustomAdapter(
											context,
											(List<Map<String, Object>>) contents,
											R.layout.list_item_message, keys,
											new int[] { R.id.textView1,
													R.id.textView2,
													R.id.textView3,
													R.id.textView4,
													R.id.textView5 });
									setListAdapter(adapter);
								}
							} else {
								adapter.notifyDataSetChanged();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							page--;
							if (code != 0) {
								loadFailed(mesage);
							} else {
								loadSuccessed();
								page++;
							}
						}

					}
				});
	}

	protected void setListAdapter(SimpleCustomAdapter adapter) {
		if (listView != null && adapter != null) {
			listView.setAdapter(adapter);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception.
		try {
			mCallback = (OnFragmentEvent) activity;
		} catch (ClassCastException e) {
			lg.e(TAG, "this activity not implents OnFragmentEvent");
		}
	}

	@Override
	public void onItemClick(AdapterView<?> l, View v, int position, long id) {
		// if (mCallback != null) {
		// mCallback.onArticleSelected(position);
		// }
		// // getListView().setItemChecked(position, true);
		// try {
		// GlobalVariable.getGlobalInstance().intent.putExtra(
		// IntentExtraDataKey.MESSAGE_INFO_ID,
		// userListJosnAry.getJSONObject(position).optInt(
		// IntentExtraDataKey.RESERVEID));
		// GlobalVariable.getGlobalInstance().intent.putExtra(
		// IntentExtraDataKey.MESSAGE_INFO_TYPE,
		// IntentExtraDataKey.RESERVEID);
		// } catch (JSONException e) {
		// e.printStackTrace();
		// } catch (NullPointerException e) {
		// e.printStackTrace();
		Toast.makeText(getActivity(), "no action", Toast.LENGTH_SHORT).show();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.sendMessage:
			Tip.show("sendmeaage");
			if (editText1.getText() != null && editText1.getText().length() > 0) {
				sendMessageToSingleCarer(editText1.getText().toString());
			} else {
				editText1.requestFocus();
				editText1.setError(getString(R.string.error_field_required));
			}

			break;
		case R.id.pickImage:

			if (mCallback != null) {
				mCallback.onFragmentClick(v);
			} else {
				Tip.show("pick an image");
			}
			break;

		default:
			break;
		}

	}

	private void sendMessageToSingleCarer(String content) {
		ds.sendMessage(
				content,
				"SMS",
				"-- from android",
				imageUrl,
				IntentExtraDataKeyValue.getUserInfoToIntent().optString(
						"identifier"), null,
				new AjaxCallBackProxy<String>(view.findViewById(R.id.loading)) {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						lg.e(TAG, "sendMessageToSingleCarer" + t);
						try {
							JSONObject result = new JSONObject(t);
							String reason = result.optString("reason");
							if (TextUtils.isEmpty(reason)) {
								page = 1;
								getdata(page);
							} else {
								Tip.show(reason);
							}
						} catch (JSONException e) {
							Tip.show(e.getMessage());
							e.printStackTrace();
						}

					}
				});

	}

	public void receiveImageUploadResult(String message, Intent intent) {
		if (TextUtils.isEmpty(message)) {
			return;
		}
		// [{"productImage":"uploads/20130927/88619415-c623-4dbe-820f-80d74321b156.png","thumbnailImage":"thumbnail/20130927/1380269483669.jpg"}]
		JSONArray temp;
		try {
			temp = new JSONArray(message);
			imageUrl = temp.optJSONObject(0).optString("productImage");
			ImageView pickImage = (ImageView) view.findViewById(R.id.pickImage);
			// ImageLoader.getInstance().displayImage(
			// GlobalVariable.URL_image_down + imageUrl, pickImage);
			String localImageUrl = intent
					.getStringExtra(ImageUploadActivity.LocalImageUrl);
			ImageLoader.getInstance().displayImage("file://" + localImageUrl,
					pickImage);
			pickImage.setTag(intent
					.getStringExtra(ImageUploadActivity.LocalImageUrl));
			pickImage.startAnimation(AnimationUtils.loadAnimation(context,
					R.anim.fade_in_two_second));
			lg.i(TAG, "receiveImageUploadResult:" + imageUrl);
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}
}